package com.yuehuanghun.admin.core.config.satoken;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yuehuanghun.admin.core.domain.SysRole;
import com.yuehuanghun.admin.core.service.ISysMenuService;
import com.yuehuanghun.admin.core.service.ISysRoleService;
import com.yuehuanghun.admin.core.service.ISysUserService;

import cn.dev33.satoken.stp.StpInterface;

@Component
public class YadminStpInterface implements StpInterface {
	@Autowired
	private ISysRoleService sysRoleService;
	@Autowired
	private ISysMenuService sysMenuService;
	@Autowired
	private ISysUserService sysUserService;

	@Override
	public List<String> getPermissionList(Object loginId, String loginType) {
		String userName = (String) loginId;
		Long userId = sysUserService.getUserByUserName(userName).getUserId();
		
		Set<String> roles = sysRoleService.getRolesByUserId(userId).stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
		
		Set<String> perms;
		if(roles.contains("admin")) { //admin角色拥有所有权限 TODO 常量
			perms = new HashSet<>();
			perms.add("*:*:*");
		} else {
			perms = sysMenuService.getMenuPermsByUserId(userId);
		}

		return perms.stream().collect(Collectors.toList());
	}

	@Override
	public List<String> getRoleList(Object loginId, String loginType) {
		String userName = (String) loginId;
		Long userId = sysUserService.getUserByUserName(userName).getUserId();
		Set<String> roles = sysRoleService.getRolesByUserId(userId).stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
		return roles.stream().collect(Collectors.toList());
	}

}
